package handlers

import (
	"encoding/json"
	"github.com/gin-gonic/gin"
	"socia-shop/cache"
	"socia-shop/model"
	"socia-shop/pkg"
	"strconv"
	"time"
)

func Login(c *gin.Context) {
	username := c.PostForm("username")
	password := c.PostForm("password")
	if username == "" || password == "" {
		c.JSON(200, gin.H{
			"code": 200,
			"msg":  "字段不可为空",
		})
		return
	}

	var user model.User
	err := model.DB.Where("username = ?", username).First(&user).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "查询失败",
		})
		return
	}

	if user.ID == 0 {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "用户不存在",
		})
		return
	}

	if user.Password != pkg.Md5Str(password) {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "密码错误",
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "登录成功",
	})
	return

}

func Add(c *gin.Context) {
	title := c.PostForm("title")
	content := c.PostForm("content")
	author := c.PostForm("author")

	if title == "" || content == "" || author == "" {
		c.JSON(200, gin.H{
			"code": 200,
			"msg":  "字段不可为空",
		})
		return
	}

	data := model.Social{
		Title:   title,
		Content: content,
		Author:  author,
	}
	err := model.DB.Create(&data).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "发布失败",
		})
		return
	}
	//设置缓存
	redis_key := "social_id_" + strconv.Itoa(int(data.ID))
	var social model.Social
	model.DB.Where("id = ?", data.ID).First(&social)           //查找数据
	jsonData, _ := json.Marshal(social)                        //转化为json格式
	cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2) //保存到redis中
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "发布成功",
	})
	return

}
func Detail(c *gin.Context) {
	id := c.Query("id")

	var social model.Social
	model.DB.Where("id = ?", id).First(&social)
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "查询成功",
		"data": social,
	})
	return

}
func Del(c *gin.Context) {
	id := c.Query("id")
	model.DB.Where("id = ?", id).Delete(&model.Social{}, id)

	redis_key := "social_id_" + id
	cache.Rdb.Del(cache.Ctx, redis_key)

	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "删除成功",
	})
	return

}
func List(c *gin.Context) {
	var social []model.Social

	redis_key := "list_"

	cacheDate, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if cacheDate == "" {
		model.DB.Find(&social)
		jsonData, _ := json.Marshal(social)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)

	} else {
		json.Unmarshal([]byte(cacheDate), &social)

	}

	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "查询成功",
		"data": social,
	})
	return
}
